﻿@inject IHttpService _httpService

@inject IPopupService PopupService

@inject NavigationManager NavigationManager


<div style="display:flex;">
    <Button Icon="fa fa-pencil" Text="编辑" Color="Color.Success" IsAsync="true" OnClick="OnEdit" Size="Size.ExtraSmall" style=" width: 80px;" class="me-3" />
    @if (Model.IsHidden)
    {
        <Button Icon="fa fa-map-signs" Text="显示" Color="Color.Primary" IsAsync="true" OnClickWithoutRender="@(()=>OnClickVoted(false))" Size="Size.ExtraSmall" style=" width: 80px;" />

    }
    else
    {
        <Button Icon="fa fa-unlink" Text="隐藏" Color="Color.Danger" IsAsync="true" OnClickWithoutRender="@(()=>OnClickVoted(true))" Size="Size.ExtraSmall" style=" width: 80px;" />
    }
</div>

@code {
    [Parameter]
    public VoteViewModel Model { get; set; }
    [Parameter]
    public EventCallback StateChanged { get; set; }

    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    public async Task OnClickVoted(bool isHidden)
    {
        string text = isHidden ? "隐藏" : "显示";

        try
        {
            var obj = await _httpService.PostAsync<HiddenVoteModel, Result>("api/votes/HiddenVote", new HiddenVoteModel { Ids = new long[] { Model.Id }, IsHidden = isHidden });
            //判断结果
            if (obj.Successful == false)
            {
                await PopupService.ToastErrorAsync(text+"投票失败", obj.Error);
            }
            else
            {
                await PopupService.ToastSuccessAsync(text + "投票成功", text + "投票成功");
                await StateChanged.InvokeAsync();
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, text + "投票失败");
        }
    }

    public void OnEdit()
    {
        NavigationManager.NavigateTo("/votes/editvote/" + Model.Id);
        
    }
}
